﻿Imports SISSAT.BusinessLayer.DomainModels
Imports SISSAT.BusinessLayer.Services

Namespace Views
    Public Class SubjectDetailControlPresenter

        Private Property View As ISubjectDetailControlView
        Private Property Service As ISubjectService

        Public Sub New(view As ISubjectDetailControlView)
            Service = New SubjectService
            Me.View = view
            AddHandler Me.View.OnClear, AddressOf OnClear
            AddHandler Me.View.OnInitialization, AddressOf OnInitialization
            AddHandler Me.View.OnSubmit, AddressOf OnSubmit
        End Sub

        Private Sub OnClear()
            Me.View.Code = String.Empty
            Me.View.Description = String.Empty
            Me.View.Name = String.Empty
            Me.View.Units = String.Empty

            OnInitialization()
        End Sub

        Private Sub OnInitialization()
            Dim entity As Subject = Nothing
            If Me.View.SubjectId > 0 Then
                entity = Service.ReadById(Me.View.SubjectId)
            ElseIf Me.View.ScheduleId > 0 Then
                Dim service As IScheduleService = New ScheduleService
                Dim schedule As Schedule = service.ReadById(Me.View.ScheduleId)
                entity = schedule.Subject
            Else
                Return
            End If

            Me.View.Code = entity.Code
            Me.View.Description = entity.Description
            Me.View.Name = entity.Name
            Me.View.Units = Convert.ToString(entity.Units)
        End Sub

        Private Sub OnSubmit()
            If Me.View.SubjectId = 0 Then
                Dim units As Decimal = Convert.ToDecimal(Me.View.Units)
                Service.Create(Me.View.Code, Me.View.Description, Me.View.Name, units, Me.View.CurrentUserId)

                Return
            End If

            Dim entity As Subject = Service.ReadById(Me.View.SubjectId)
            entity.Code = Me.View.Code
            entity.Description = Me.View.Description
            entity.Name = Me.View.Name
            entity.Units = Convert.ToDecimal(Me.View.Units)
            Service.Edit(entity, Me.View.CurrentUserId)
        End Sub

    End Class
End Namespace

